package com.cy.mall.web.front;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.cy.mall.service.order.OrderJobService;
import com.cy.mall.service.order.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cy.mall.comm.constant.Constants;
import com.cy.mall.comm.exception.MsgException;
import com.cy.mall.comm.utils.CommonUtils;
import com.cy.mall.model.Result;
import com.cy.mall.model.ao.customer.BankmaCustomerAddAO;
import com.cy.mall.model.ao.customer.CustomerLoginAO;
import com.cy.mall.model.ao.sms.SmsCodeAO;
import com.cy.mall.model.domain.customer.BankmaCustomer;
import com.cy.mall.model.dto.customer.CustomerLoginDTO;
import com.cy.mall.model.enums.CheckResult;
import com.cy.mall.service.comm.BigDataService;
import com.cy.mall.service.comm.FaceIDCertificateService;
import com.cy.mall.service.comm.SmsService;
import com.cy.mall.service.customer.BankmaCustomerService;
import com.cy.mall.service.customer.CustomerService;
import com.cy.mall.web.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 前台-公用方法
 *
 * @author tanyilin
 *
 * @create 2019年1月22日 下午4:56:59
 */
@RestController
@RequestMapping("/home")
@Api(tags = "前台-公用方法")
public class HomeController extends BaseController {

	@Autowired
    private BankmaCustomerService    bankmaCustomerService;
	@Autowired
    private SmsService               smsService;
	@Autowired
	private CustomerService          customerService;
	@Autowired
	private FaceIDCertificateService faceIDCertificateService;
	@Autowired
	private BigDataService           bigDataService;
	@Autowired
	private OrderService             orderService;
	@Autowired
	private OrderJobService          orderJobService;
	
	@ApiOperation("测试")
	@GetMapping("/hello")
	public String hello() {
		return "你好，马先生";
	}
	
	@ApiOperation("清除缓存")
	@GetMapping("/clear/cache")
	public Result clearCache(@RequestParam(value = "prexKey") String prexKey) {
		//根据key前缀,模糊删除
		Set<String> keys = this.redisTemplate.keys(prexKey);
		this.redisTemplate.delete(keys);
		return ok();
	}
	
	@ApiOperation("新增bankma马先生官网咨询客户信息")
    @PostMapping("/do/add/bankma/customer")
    public Result addBankmaCustomer(@Validated BankmaCustomerAddAO addAO, BindingResult bindingResult) {
    	this.checkError(bindingResult);
    	BankmaCustomer bankmaCustomer = new BankmaCustomer();
    	BeanUtils.copyProperties(addAO, bankmaCustomer);
    	bankmaCustomerService.addBankmaCustomer(bankmaCustomer);
    	return ok();
    }
	
	@ApiOperation("发送短信验证码")
    @PostMapping("/send/sms/code")
	public Result sendSmsCode(@Validated SmsCodeAO smsCodeAO, BindingResult bindingResult) {
		
		this.checkError(bindingResult);
		smsCodeAO.setMobile(smsCodeAO.getMobile().replace(" ", ""));
		
		String key = CommonUtils.smsCodeKey(smsCodeAO.getMobile(), smsCodeAO.getSmsType());
		if (redisTemplate.hasKey(key)) {
            return ok("验证码已发送", redisTemplate.getExpire(key, TimeUnit.SECONDS));
        }
		
		String code = Constants.IS_PROD ? CommonUtils.randomCode(4) : "8888";
		Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        Result result = smsService.send(smsCodeAO.getMobile(), smsCodeAO.getSmsType(), params);
        if (result.isOk()) {
            redisTemplate.opsForValue().set(key, code, 10, TimeUnit.MINUTES);
            result.setData(10 * 60);
        }

        return result;
	}
	
	@ApiOperation("用户登录")
    @PostMapping("/login")
	public Result<CustomerLoginDTO> login(@Validated CustomerLoginAO loginAO, BindingResult bindingResult) {
		
		this.checkError(bindingResult);
		loginAO.setMobile(loginAO.getMobile().replace(" ", ""));
		
		//验证短信验证码
		this.checkSmsCode(loginAO.getMobile(), loginAO.getCode(), loginAO.getSmsType());
		
		//登录或注册
		Result loginResult = customerService.login(loginAO);
		
		//得到登录的客户信息
		CustomerLoginDTO customerLoginDTO = (CustomerLoginDTO) loginResult.getData();

//		if(!CheckResult.PASS.equals(customerLoginDTO.getFaceidCheckResult())) {
//			//如果未进行faceid人脸识别，或者人脸识别失败过的，则进入人脸识别流程
//			Result<Map<String, Object>> getBizTokenResult = faceIDCertificateService.getBizToken();
//			if(!getBizTokenResult.isOk()) {
//				throw new MsgException("请求获取人脸识别 biz_token 失败");
//			}
//			//得到 biz_token、url
//			Map<String, Object> map = getBizTokenResult.getData();
//			String bizToken = map.get("BizToken").toString();
//			String url = map.get("Url").toString();
//
//			//更新biz_token
//			customerService.updateBizToken(customerLoginDTO.getCustomerId(), bizToken);
//
//			customerLoginDTO.setFaceIDLiteUrl(url);
//		}

		return ok("", customerLoginDTO);
	}

	@ApiOperation("post传递form表单参数")
    @PostMapping("/post/form")
	public Result postForm() {
		return bigDataService.postForm();
	}
	
	@ApiOperation("post传递json参数")
    @PostMapping("/post/json")
	public Result postJson() {
		return bigDataService.postJson();
	}

	@ApiOperation("通过客户手机号码删除订单数据")
	@GetMapping("/delete/order")
	public Result deleteAllOrderByMobile(@RequestParam(value = "mobile") String mobile) {
		orderService.deleteAllOrderByMobile(mobile);
		return ok("清除成功");
	}

	@ApiOperation("通过客户手机号码删除实名认证记录")
	@GetMapping("/delete/auth/record")
	public Result deleteAuthRecordByMobile(@RequestParam(value = "mobile") String mobile) {
		customerService.deleteCustomerAuthRecord(mobile);
		return ok("清除成功");
	}

	@ApiOperation("测试还款提醒消息发送")
	@GetMapping("/test/repaymentRemind")
	public Result testRepaymentRemind() {
		orderJobService.doRepaymentRemind();
		return ok();
	}

}
